#coding=utf8

from django.db import models
from djangosphinx.models import SphinxSearch
from valkyrie.models.consts import CAT_NAME_DICT

import logging

logger = logging.getLogger('django')


class Subject(models.Model):
    id = models.IntegerField(max_length=10, primary_key=True, unique=True)
    name = models.CharField(max_length=255)
    cat_id = models.SmallIntegerField(max_length=6)
    subtype = models.CharField(max_length=16)
    intro = models.TextField()
    created_at = models.DateTimeField(null=False)

    search = SphinxSearch(
        index='valk',
        weights={
            'name': 95,
            'intro': 5,
        },
    )

    @property
    def cat_desc(self):
        return CAT_NAME_DICT.get(self.cat_id, '')


class DownloadItem(models.Model):
    id = models.AutoField(max_length=10, primary_key=True, unique=True, auto_created=True)
    subject_id = models.IntegerField(max_length=10)
    url = models.TextField()
    url_title = models.TextField()
    size = models.CharField(max_length=26)


def subject_search(q):
    q = Subject.search.query(q).set_options(passages=True)
    # diff on Mac and Linux?
    d = q._get_results()
    data = d['matches']
    ret = []
    for d in data:
        ret.append(Subject.objects.get(pk=d['id']))

    total_num = q.count()
    #ret = list(q)
    return total_num, ret
